package com.blakequ.androidblemanager.ui;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import androidx.annotation.Nullable;

import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.blakequ.androidblemanager.BuildConfig;
import com.blakequ.androidblemanager.R;
import com.blakequ.androidblemanager.adapter.DeviceListAdapter;
import com.blakequ.androidblemanager.containers.BluetoothLeDeviceStore;
import com.blakequ.androidblemanager.databinding.PageMainBindingImpl;
import com.blakequ.androidblemanager.event.UpdateEvent;
import com.blakequ.androidblemanager.service.MyService;
import com.blakequ.androidblemanager.service.MyServiceKeYiYunXing;
import com.blakequ.androidblemanager.ui.scan.DeviceDetailsActivity;
import com.blakequ.androidblemanager.utils.BLEUtil;
import com.blakequ.androidblemanager.utils.BluetoothUtils;
import com.blakequ.androidblemanager.utils.Constants;
import com.blakequ.androidblemanager.utils.IntentUtils;
import com.blakequ.androidblemanager.utils.LocationUtils;
import com.blakequ.androidblemanager.utils.PreferencesUtils;
import com.blakequ.androidblemanager.widget.MyAlertDialog;
import com.blakequ.bluetooth_manager_lib.device.BluetoothLeDevice;
import com.pgyer.pgyersdk.PgyerSDKManager;
import com.pgyer.pgyersdk.callback.CheckoutVersionCallBack;
import com.pgyer.pgyersdk.model.CheckSoftModel;
import com.tamsiree.rxkit.RxActivityTool;
import com.tamsiree.rxkit.RxAppTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.PermissionUtils;

public class MainPage extends BaseActivity implements AdapterView.OnItemClickListener{
    @BindView(R.id.tvBluetoothLe)
    protected TextView mTvBluetoothLeStatus;
    @BindView(R.id.tvBluetoothStatus)
    protected TextView mTvBluetoothStatus;
    @BindView(R.id.tvBluetoothFilter)
    protected TextView mTvBluetoothFilter;
    @BindView(R.id.tvBluetoothPeriod)
    protected TextView mTvBlePeriod;
    @BindView(R.id.tvItemCount)
    protected TextView mTvItemCount;
    @BindView(android.R.id.list)
    protected ListView mList;
    @BindView(android.R.id.empty)
    protected View mEmpty;
    @BindView(R.id.log)
    protected TextView log;
    @BindView(R.id.restart)
    protected Button restart;
    private View rootView;


    boolean isVisible = false;
    private DeviceListAdapter mLeDeviceListAdapter;
    //    private BluetoothUtils mBluetoothUtils;
//    private BluetoothLeDeviceStore mDeviceStore;
    boolean isInited = false;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.page_main);
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);
//        mDeviceStore = new BluetoothLeDeviceStore();
//        mBluetoothUtils = new BluetoothUtils(this);
        mLeDeviceListAdapter = new DeviceListAdapter(this);
        mList.setEmptyView(mEmpty);
        mList.setOnItemClickListener(this);
        mList.setAdapter(mLeDeviceListAdapter);
        updateItemCount(0);
        restart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                restartApp();
            }
        });
    }


    @Override
    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        if (!isInited) {
            Intent intent = new Intent(this, MyService.class);
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(intent);
                }
                else{
                    startService(intent);
                }
            } catch (Exception e) {
                PgyerSDKManager.reportException(e);
            }
            isInited = true;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private BluetoothUtils getUtil() {
        return BLEUtil.getInstance().getmBluetoothUtils();
    }

    private void refreshView() {
        if (getUtil() == null) {
            return;
        }
        final boolean mIsBluetoothOn = getUtil().isBluetoothOn();
        final boolean mIsBluetoothLePresent = getUtil().isBluetoothLeSupported();

        if (mIsBluetoothOn) {
            mTvBluetoothStatus.setText(R.string.on);
        } else {
            mTvBluetoothStatus.setText(R.string.off);
        }

        if (mIsBluetoothLePresent) {
            mTvBluetoothLeStatus.setText(getString(R.string.supported) + " " + RxAppTool.getAppVersionName(this) + "("+RxAppTool.getAppVersionCode(this)+")");
        } else {
            mTvBluetoothLeStatus.setText(getString(R.string.not_supported) + " " + RxAppTool.getAppVersionName(this) + "("+RxAppTool.getAppVersionCode(this)+")");
        }

        String filterName = PreferencesUtils.getString(this, Constants.FILTER_NAME, "");
        int filterRssi = PreferencesUtils.getInt(this, Constants.FILTER_RSSI, -100);
        boolean filterSwitch = PreferencesUtils.getBoolean(this, Constants.FILTER_SWITCH, false);
        if (filterSwitch){
            if (filterName != null && filterName.length() > 0){
                mTvBluetoothFilter.setText("FilterName:"+filterName+" ,FilterRssi:"+filterRssi);
            }else {
                mTvBluetoothFilter.setText("FilterRssi:"+filterRssi);
            }
            int scanPeriod = PreferencesUtils.getInt(this, Constants.SCAN_PERIOD, 10*1000);
            int pausePeriod = PreferencesUtils.getInt(this, Constants.PAUSE_PERIOD, 5*1000);
            mTvBlePeriod.setText("scan:"+scanPeriod/1000+"s, pause:"+pausePeriod/1000+"s");
        }else {
            mTvBluetoothFilter.setText(R.string.off);
        }
    }
    @Override
    public void onResume() {
        super.onResume();

        isVisible = true;

        checkUpdate();
//        BLEUtil.getInstance().requestSubmit("");
    }

    @Override
    protected void onPause() {
        super.onPause();
        isVisible = false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRefresh(UpdateEvent event){
        if (!isVisible) {
            return;
        }
        refreshView();
        switch (event.getType()){
            case SCAN_UPDATE:
                if (this != null){
                    log.setText("扫描结果 共接收:"+event.getReceiveTimes()+" 接口请求"+BLEUtil.getInstance().getSendTimes()
                            +"次 成功"+BLEUtil.getInstance().getSuccessTimes() + " 失败" +BLEUtil.getInstance().getFailedTimes());
                    BluetoothLeDeviceStore store = event.getStore();
                    if (store != null){
                        mLeDeviceListAdapter.refreshData(store.getDeviceList());
                        updateItemCount(mLeDeviceListAdapter.getCount());
                    }
                }
                break;
            case CONFIG_CHANGE:
                int scrodKey = PreferencesUtils.getInt(this, Constants.SHOW_SPINNER, -1);
                mLeDeviceListAdapter.updateConfig(scrodKey);
                break;
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        final BluetoothLeDevice device = (BluetoothLeDevice) mLeDeviceListAdapter.getItem(position);
//        if (device == null) return;
//
//        final Intent intent = new Intent(this, DeviceDetailsActivity.class);
//        intent.putExtra(DeviceDetailsActivity.EXTRA_DEVICE, device);
//
//        startActivity(intent);
    }

    private void updateItemCount(final int count) {
        mTvItemCount.setText(getString(R.string.formatter_item_count, String.valueOf(count)));
    }




    private void checkUpdate() {
        PgyerSDKManager.checkSoftwareUpdate(MainPage.this, new CheckoutVersionCallBack() {
            @Override
            public void onSuccess(CheckSoftModel checkSoftModel) {
                if (checkSoftModel != null && checkSoftModel.isBuildHaveNewVersion()) {
                    AlertDialog dialog = new AlertDialog.Builder(MainPage.this)
                            .setPositiveButton("去下载", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int i) {
                                    Intent intent = new Intent();
                                    intent.setAction("android.intent.action.VIEW");
                                    Uri targetUrl = Uri.parse(checkSoftModel.getDownloadURL());
                                    intent.setData(targetUrl);
                                    startActivity(intent);
                                    dialog.cancel();
                                }
                            })
                            .setNegativeButton("返回", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            })
                            .setCancelable(false)
                            .setTitle("发现新版本"+checkSoftModel.getBuildVersion()+"\n"+checkSoftModel.getDownloadURL())
                            .setMessage(""+checkSoftModel.getBuildUpdateDescription())
                            .create();
                    dialog.show();
                }
            }

            @Override
            public void onFail(String s) {

            }
        });
    }


}
